package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.User;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员对采购员管理层
 */
public class BuyerAdminActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView buyerListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_admin);
        //        实例化
        dbOpenHelper = new DBOpenHelper(BuyerAdminActivity.this, "db_kindheartedness", null, 1);
//        获取按钮控制权
        Button buyerAddBtn = findViewById(R.id.buyerAddBtn);
        buyerAddBtn.setOnClickListener(this);
//        获取listView控制权
        buyerListView = findViewById(R.id.queryBuyerListView);
//        渲染所有采购员
        /**
         * 查询出所有的采购员信息并进行回显
         */
        findAllBuyer();
//        添加长按点击弹出选项框菜单
        buyerListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0, 0, 0, "详情");
                menu.add(0, 1, 0, "删除");
            }
        });

    }

    /**
     * 获取所有的采购员
     */
    private void findAllBuyer() {
//        获取打开的数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("user", null, "type = ? ", new String[]{"3"}, null, null, null);
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(50);
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String userName = cursor.getString(1);
            String phone = cursor.getString(2);
            String createTime = cursor.getString(11);
            Integer sex = null;
            try {
                sex = Integer.valueOf(cursor.getString(6));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("BuyerAdminActivity.java", "数据不能转化为数字,请检查！");
            }
            String sexStr = sex == 0 ? "男" : "女";
//                对数据进行封装
            map.put("userName", userName);
            map.put("phone", phone);
            map.put("sex", sexStr);
            map.put("createTime", createTime);
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
        //        判断是否具有采购员
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, BuyerAdminActivity.this, "暂时没有采购员，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                BuyerAdminActivity.this,
                resultList,
                R.layout.query_buyer,
                new String[]{
                        "userName", "phone",
                        "sex", "createTime"
                },
                new int[]{
                        R.id.buyerName, R.id.buyerPhone,
                        R.id.buyerSex, R.id.buyerCreateTime
                }
        );
        buyerListView.setAdapter(simpleAdapter);
    }


    /**
     * 给菜单项添加事件
     *
     * @param item 菜单索引
     * @return
     */
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView buyerPhone = targetView.findViewById(R.id.buyerPhone);
//                获取元素内容 手机号
        String buyerPhoneToString = buyerPhone.getText().toString();
        Log.i("=====ListView列表绑定的ID==", id);
        Log.i("===== 对应的采购员手机号==", buyerPhoneToString);
        switch (item.getItemId()) {
            case 0:
                // TODO: 2021/12/19 完成事件操作(已完成)
//                更新事件的方法
                updateDiaLog(buyerPhoneToString);
                return true;
            case 1:
//                删除事件的方法
                deleteData(buyerPhoneToString);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 删除采购员
     *
     * @param buyerPhoneToString 手机号
     */
    private void deleteData(final String buyerPhoneToString) {
//        建立一个对话框
//                添加一个弹出对话框
        AlertDialog alertDialog = new AlertDialog.Builder(BuyerAdminActivity.this).create();
//                设置提示
        alertDialog.setMessage("确定要删除该采购员吗？");
//                设置 确认按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                int delete = readableDatabase.delete("user", "phone = ?", new String[]{buyerPhoneToString});
                if (delete >= 1) {
                    Log.i("BuyerAdminActivity.java", "删除成功,删除记录数：" + delete);
                    toast = ToastUtil.toastHint(toast, BuyerAdminActivity.this, "删除成功！");
                    startActivityForResult(new Intent(BuyerAdminActivity.this, BuyerAdminActivity.class), RESULT_OK);
                    finish();
                    return;
                }
                toast = ToastUtil.toastHint(toast, BuyerAdminActivity.this, "删除失败,请刷新重试！");
                return;
            }
        });
//        设置取消按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast = ToastUtil.toastHint(toast, BuyerAdminActivity.this, "本次操作已取消！");
                return;
            }
        });
//          显示对话框
        alertDialog.show();
    }

    /**
     * 查询采购员详情
     *
     * @param buyerPhoneToString
     */
    private void updateDiaLog(String buyerPhoneToString) {
        //        获取打开的数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        查询手机号对应的采购员信息
        Cursor cursor = readableDatabase.query("user", null, "type = ? and phone = ? ", new String[]{"3", buyerPhoneToString}, null, null, null);
        User user = null;
        while (cursor.moveToNext()) {
            Integer id = null, sex = null, age = null;
            try {
                id = Integer.valueOf(cursor.getString(0));
                sex = Integer.valueOf(cursor.getString(6));
                age = Integer.valueOf(cursor.getString(7));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("BuyerAdminActivity.java", "数据转化数字失败，请检查数据！");
            }
            String userName = cursor.getString(1);
            String phone = cursor.getString(2);
            String idNumber = cursor.getString(8);
            String address = cursor.getString(9);
            user = new User();
            user.setId(id);
            user.setUserName(userName);
            user.setPhone(phone);
            user.setSex(sex);
            user.setAge(age);
            user.setIdNumber(idNumber);
            user.setAddress(address);
        }
        if (user == null) {
            toast = ToastUtil.toastHint(toast, BuyerAdminActivity.this, "未查到此数据,请刷新重试！");
            return;
        }
        String toJSONString = JSON.toJSONString(user);
//        存储集合进行传递
        Bundle bundle = new Bundle();
        bundle.putString("buyer", toJSONString);
        intent = new Intent(BuyerAdminActivity.this, BuyerUpdateActivity.class);
//         指向更新页面
        intent.putExtras(bundle);
        startActivity(intent);
        BuyerAdminActivity.this.finish();
    }

    /**
     * 按钮点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buyerAddBtn:
                intent = new Intent(BuyerAdminActivity.this, BuyerAddActivity.class);
                startActivity(intent);
                BuyerAdminActivity.this.finish();
                break;
            default:
                break;
        }
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}

